package com.shanghai.market.plshnaghai.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.shanghai.market.plshnaghai.AppApplication;
import com.shanghai.market.plshnaghai.PopWindows.HeadPortraitPopWindow;
import com.shanghai.market.plshnaghai.R;
import com.shanghai.market.plshnaghai.TabsActivity;
import com.shanghai.market.plshnaghai.abstracts.AbstractModelPost;
import com.shanghai.market.plshnaghai.constants.constant;
import com.shanghai.market.plshnaghai.entity.AppData;
import com.shanghai.market.plshnaghai.entity.login.MaterialWrite;
import com.shanghai.market.plshnaghai.interfaces.IObjectView;
import com.shanghai.market.plshnaghai.model.login.MaterialWriteModel;
import com.shanghai.market.plshnaghai.net.VolleyParams;
import com.shanghai.market.plshnaghai.publics.BaseActivity;
import com.shanghai.market.plshnaghai.publics.LogCat;
import com.shanghai.market.plshnaghai.utils.DisplayUtils;
import com.shanghai.market.plshnaghai.utils.ImageUtils;
import com.shanghai.market.plshnaghai.utils.Utils;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

//import net.sf.json.JSONObject;

/**
 * 注册资料
 */
public class MaterialWriteActivity extends BaseActivity implements View.OnClickListener, IObjectView<MaterialWrite> {

    private RadioButton mButtonBoy;
    private RadioButton mButtonWoman;
    private RadioGroup mRadioGroup;
    private EditText mTextViewName;
    private TextView mTextViewConfirm;
    private int mSex;
    private String phone;
    private ImageView mImageViewLogin;
    private HeadPortraitPopWindow mHeadPortraitPopWindow;
    private LinearLayout mLinearLayout;
    private String mBtmBase64;
    private AbstractModelPost model;

    @Override
    public void initParms() {
        if (getIntent() != null) {
            phone = getIntent().getStringExtra("phone");
            LogCat.i("phone +MaterialWriteActivity ..." + phone);
        }

    }

    @Override
    public View bindView() {
        View view = LayoutInflater.from(this).inflate(R.layout.activity_material_write, null);
        return view;
    }

    @Override
    public int bindLayout() {
        return 0;
    }

    @Override
    public void initView(View view) {
        mButtonBoy = (RadioButton) view.findViewById(R.id.radioButton_boy);
        mButtonWoman = (RadioButton) view.findViewById(R.id.radioButton_woman);
        mRadioGroup = (RadioGroup) view.findViewById(R.id.rg_group);
        mTextViewName = (EditText) view.findViewById(R.id.editText_name);
        mTextViewConfirm = (TextView) view.findViewById(R.id.textview_confirm);
        mImageViewLogin = (ImageView) view.findViewById(R.id.roundedimageview);
        mLinearLayout = (LinearLayout) view.findViewById(R.id.LinearLayout);
    }


    @Override
    public void setListener() {
        mImageViewLogin.setOnClickListener(this);
    }

    @Override
    public void doBusiness(Context mContext) {
        mBarTitle.setText("资料填写");
        mHeadPortraitPopWindow = new HeadPortraitPopWindow(this);
        model = new MaterialWriteModel(MaterialWriteActivity.this);
        //设置自己的样式
        mButtonBoy.setButtonDrawable(R.drawable.radiobutton_selector);
        mButtonWoman.setButtonDrawable(R.drawable.radiobutton_selector);


        mTextViewConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //        <!--判断用户名为空 -->
                String name = mTextViewName.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    showToast("昵称不能为空");
                    return;
                }

                // <!--判断选中的性别-->
                int checkedRadioButtonId = mRadioGroup.getCheckedRadioButtonId();

//        <!--判断具体选中的性别 -->
                mSex = 0; //定义一个变量默认值为0 作用就是做一个标识
                switch (checkedRadioButtonId) {
                    case R.id.radioButton_boy: //选中的是男
                        mSex = 1;
                        break;
                    case R.id.radioButton_woman: //选中的是女
                        mSex = 2;
                        break;
                    default:
                        break;
                }


                showToast(name);
                //    <!--判断性别 -->
                if (mSex == 0) {
                    showToast("请选性别");
                    return;
                }
                VolleyParams params = new VolleyParams();
                params.put("mobile", phone);
                params.put("nickname", name);
                params.put("sex", mSex + "");
                params.put("headpic", mBtmBase64);
                model.setParams(params);

//                VolleyParams params = new VolleyParams();
//                params.put("nickname", name);
//                params.put("sex", mSex + "");
//                params.put("headpic", mBtmBase64);
//                params.put("type", 2 + "");
//                params.put("qquid", "qq1111");
//                model.setParams(params);

                model.getData();


            }
        });
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.roundedimageview:
                String mFilePath = Environment.getExternalStorageDirectory() + "/WondersGroup/" + System.currentTimeMillis()
                        + ".jpg";
                mHeadPortraitPopWindow.initPopWindow(mFilePath);
                mHeadPortraitPopWindow.showAsDropDown(mLinearLayout, 0, 0);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String imagePath = null;
        if (resultCode != RESULT_OK) { // 此处的 RESULT_OK 是系统自定义得一个常量
            LogCat.e("ActivityResult resultCode error");
            return;
        }


        if (requestCode == constant.USER_NAME) {
            if (resultCode == Activity.RESULT_OK) {
                final String name = data.getStringExtra(constant.Extra.USER_NAME);
//                mselfUserName.setText(name);
            }
        } else if (requestCode == constant.SELECT_PIC_KITKAT) {// 从图库中选择照片获取图片
            Uri uri = data.getData();
            imagePath = ImageUtils.getPath(this, uri);
            LogCat.i("path:" + imagePath);
        } else if (requestCode == constant.SELECT_PIC_KITKAT) {
            imagePath = ImageUtils.getPath(this, data);
            LogCat.i("path:" + imagePath);
        } else if (requestCode == constant.SELECT_CAMERA) {// 拍照获取图片
            imagePath = mHeadPortraitPopWindow.getImagePath();
            LogCat.i("path:" + imagePath);
        }

        if (!TextUtils.isEmpty(imagePath)) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 3;
            final Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
            if (bitmap != null) {
                // 为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
                Bitmap smallBitmap = zoomBitmap(bitmap, DisplayUtils.dpToPx(this, 80), DisplayUtils.dpToPx(this, 80));
                // 释放原始图片占用的内存，防止out of memory异常发生
                bitmap.recycle();

//                mImageManager.executeRequest(Request.Method.POST, UrlConstants.HEAD_LOGO, smallBitmap);
                mBtmBase64 = Utils.bitmapToBase64(smallBitmap);
                LogCat.i("mBtmBase64 ..." + mBtmBase64);
                LogCat.i("smallBitmap ..." + smallBitmap.toString());
                mImageViewLogin.setImageBitmap(smallBitmap);
            }
        }
    }

    /**
     * 缩放Bitmap图片
     **/
    private Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }

    public void saveHeadImage(Bitmap photo, String spath) {
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(spath, false));
            photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void failure(String message) {

    }

    @Override
    public void success(MaterialWrite materialWrite) {
        if (materialWrite != null) {
            AppApplication app = AppApplication.getInstance();
            AppData data = app.getAppData();
            data.setPhone(materialWrite.getPhone());
            data.setUserId(materialWrite.getUid());
            app.saveAppData(data);
            Intent intent = new Intent(MaterialWriteActivity.this, TabsActivity.class);
            startActivity(intent);
            showToast("TabsActivity");
        }
    }
}
